package com.fsck.k9.widget;

import java.lang.reflect.Array;
import java.util.ArrayList;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;

import com.fsck.k9.widget.R;
import com.fsck.k9.widget.MailBoxCounter.UpdateService;

public class K9WidgetConfigure extends Activity {
    static final String TAG = "K9WidgetConfigure";

    private static final String PREFS_NAME
            = "com.example.android.apis.appwidget.K9WidgetProvider";
    private static final String PREF_PREFIX_KEY = "prefix_";

    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    
    private Spinner mMailboxSpinner;
    
    public K9WidgetConfigure() {
        super();
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if they press the back button.
        setResult(RESULT_CANCELED);

        // Set the view layout resource to use.
        setContentView(R.layout.k9widget_configure);

        // Bind the action for the save button.
        findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                final Context context = K9WidgetConfigure.this;

                // When the button is clicked, save the string in our prefs and return that they
                // clicked OK.
                Account titlePrefix = (Account) K9WidgetConfigure.this.mMailboxSpinner.getSelectedItem();
                saveTitlePref(context, mAppWidgetId, titlePrefix);

                // Push widget update to surface with newly set prefix
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                appWidgetManager.updateAppWidget(mAppWidgetId, UpdateService.buildUpdate(context.getApplicationContext(),mAppWidgetId,null));

                // Make sure we pass back the original appWidgetId
                Intent resultValue = new Intent();
                resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
                setResult(RESULT_OK, resultValue);
                finish();
            }
        });
        this.mMailboxSpinner = (Spinner) findViewById(R.id.k9widget_mailbox);

        // Find the widget id from the intent. 
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If they gave us an intent without the widget id, just bail.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
        }

        ContentResolver cr = this.getContentResolver();
		
		Uri uri=Uri.parse("content://com.fsck.k9.messageprovider/accounts");
	    final Cursor accountCursor=cr.query(uri, null, null, null, null);
	    ArrayList<Account> accounts=new ArrayList<Account>();
		int position=-1;
		if(accountCursor!=null && accountCursor.moveToFirst())
			do
			{
				if(accountCursor.getColumnIndex("accountUuid")!=-1)
				{
					Log.d(K9WidgetConfigure.TAG, "Account=" + accountCursor.getString(1)+"/"+accountCursor.getInt(accountCursor.getColumnIndex("accountNumber")));
					accounts.add(new Account(accountCursor.getString(accountCursor.getColumnIndex("accountName")),accountCursor.getString(accountCursor.getColumnIndex("accountUuid")),accountCursor.getInt(accountCursor.getColumnIndex("accountNumber"))));
					
					if(accountCursor.getString(1).equals(loadTitlePref(K9WidgetConfigure.this, mAppWidgetId)));
						position=accountCursor.getPosition();
				}

			}            
			while(accountCursor.moveToNext());

		accounts.add(new Account(this.getString(R.string.k9widget_mailbox_all), "", -1));
		
		this.mMailboxSpinner.setSelection(position==-1?(accounts.size()):position);
		
        ArrayAdapter<Account> adapter = new ArrayAdapter<Account>(this, android.R.layout.simple_spinner_item, (Account[]) accounts.toArray(new Account[1]));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        this.mMailboxSpinner.setAdapter(adapter);
        
        this.mMailboxSpinner.setOnItemSelectedListener(
                new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						K9WidgetConfigure.this.findViewById(R.id.save_button).setEnabled(true);
						
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						K9WidgetConfigure.this.findViewById(R.id.save_button).setEnabled(false);
						
					}
                });
    }


    // Write the prefix to the SharedPreferences object for this widget
    static void saveTitlePref(Context context, int appWidgetId, Account account) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.putString(PREF_PREFIX_KEY + appWidgetId, account.toString(true));
        prefs.commit();
    }

    // Read the prefix from the SharedPreferences object for this widget.
    // If there is no preference saved, get the default from a resource
    static Account loadTitlePref(Context context, int appWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        String prefix = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null);
        
        return Account.valueOf(prefix);
    }

    static void deleteTitlePref(Context context, int appWidgetId) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.remove(PREF_PREFIX_KEY + appWidgetId);
        prefs.commit();
    }
}



